<!--
 * @Description: 
 * @Version: 2.0
 * @Date: 2024-04-09 15:03:16
 * @LastEditTime: 2024-06-06 09:55:35
-->
<template>
  <el-container>
    <el-config-provider>
      <router-view v-slot="{ Component, route }">
        <keep-alive>
          <component
            v-if="route.meta.keepAlive"
            :is="Component"
            :key="route.meta.activeMenuName"
          />
        </keep-alive>
        <component :is="Component" :key="route.meta.activeMenuName" />
      </router-view>
    </el-config-provider>
  </el-container>
</template>
<script setup lang="ts">
import { getParam } from "@/utils/index";
import { onMounted, provide, reactive } from "vue";
import { local } from "./utils/storage";
import { AccountResInfo } from "./api/res";
import { useRoute, useRouter } from "vue-router";
import { Routes } from "./router/routes";
import { AccountApi } from "./api/api";
import { ElMessage } from "element-plus";

export interface IStore {
  // 登录的账户信息
  accountInfo?: AccountResInfo;
  // 登录状态
  loginState: number;
}

const defaultStore = {
  loginState: 0,
};

// 全局存储数据
const store = reactive<IStore>(defaultStore);
provide<IStore>("store", store);

const route = useRoute();
const router = useRouter(); // 主要用于路由跳转

// 页面刷新时刷新token
onMounted(() => {
  const token = getParam("token");
  if (token) {
    local.set("token", token);
  }
});

onMounted(() => {
  setTimeout(async () => {
    if (route.path === Routes.LOGIN || route.path === "/") {
      return;
    }
    try {
      store.loginState = 2;
      // 检测token是否合法-尝试获取个人信息
      let ar = await AccountApi.getCurAccountInfo();
      store.accountInfo = ar;
      console.log("store.accountInfo", ar);
    } catch (error) {
      console.log("error::: ", error);
      router.replace("/");
    }
  }, 500);
});

// 监听用户数据变化
// watch(
//   () => store.accountInfo,
//   () => {
//     if (store && store.loginState === 1) {
//       init();
//     }
//   }
// );
</script>
<style scoped lang="less"></style>
